using LanqiQAwebapi.Dto;
using LanqiQAwebapi.Interface;

using LanqiQAwebapi.Models;
using LanqiQAwebapi.ToolsHader;
using Microsoft.EntityFrameworkCore;

namespace LanqiQAwebapi.Todo

{
    public class UserServer : IUserServer
    {

        private readonly LanQiQaDBContext _LanQiQaDBContext;

        private readonly ICacheService _cacheservice;
        private readonly Ijwt _ijwt;

        public UserServer(LanQiQaDBContext lanQiQaDBContext, Ijwt ijwt, ICacheService cacheservice)

        {
            _LanQiQaDBContext = lanQiQaDBContext;
            _ijwt = ijwt;
            _cacheservice = cacheservice;

        }
        public async Task<bool> UserhaveAsync(User user) { return true; }
        public async Task<bool> EdituserAsync(User user) { return true; }
        public async Task<User> GetUserAsync(User user) { var data = await _LanQiQaDBContext.Users.FirstOrDefaultAsync(); return data; }

        public async Task<User> GetUserNameAsync(string id) { var user = await _LanQiQaDBContext.Users.FirstOrDefaultAsync(); return user; }

        public async Task<List<User>> GetUsersAsync()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 用户登录颁布长期token,token
        /// </summary>
        /// <param name="userLoginByUser"></param>
        /// <returns></returns>
        public async Task<string> UserLoginByUserAsync(UserLoginByUser userLoginByUser)
        {
            //_cacheservice.AddBlackToken("123", "123");
            var HavedUser = await _LanQiQaDBContext.Users.Where(o => o.UserName == userLoginByUser.Username && o.Password == userLoginByUser.UserPwd).Select(c => new { c.UserId, c.UserName }).FirstOrDefaultAsync();
            var teeee = HavedUser;


            if (HavedUser == null)
            {
                return "还没有注册";
            }
            else if (await _cacheservice.CheckTokenIsBlackeAsync(HavedUser.UserId.ToString()/*, userLoginByUser.Token ?? ""*/))
            {
                return _ijwt.AccessTokenAsync(HavedUser.UserId.ToString(), HavedUser.UserName.ToString());
            }
            else
            {
                return "过期或者黑名单";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userLoginByphone"></param>
        /// <returns></returns>
        public async Task<string> UserLoginByphoneAsync(LoginByPhone loginByPhone)
        {
            var HavedUser = await _LanQiQaDBContext.Users.Where(o => o.Phone == loginByPhone.Phone).Select(c => new { c.Phone, c.UserId, c.UserName }).FirstOrDefaultAsync();
            if (HavedUser == null) return "你已成功注册请登录";
            var Code = await CheckMessageAsync(loginByPhone.Phone, loginByPhone.PhoneCode);
            if (Code == 1)
            {
                if (!await _cacheservice.CheckTokenIsBlackeAsync(HavedUser.UserId.ToString()/*, loginByPhone.Token*/))
                {
                    return _ijwt.AccessTokenAsync(HavedUser.UserId.ToString(), HavedUser.UserName.ToString());
                }
                else
                {
                    return "请重新登录";
                }

            }
            else if (Code == 2) { return "验证码已经过期"; }
            else { return "还没有发送验证码"; }
        }
        public async Task<string> SendPhoneMMessageCodeAsync(UserLoginByphone userLoginByphone)
        {
            
            var Messagecode = AddMessage.SendMessage(userLoginByphone.Phone);
            if (await _cacheservice.AddSendMessageAsync(userLoginByphone.Phone, Messagecode.ToString()))
            {
                return Messagecode.ToString();
            }
            return "发送次数过多请次日再试！";
        }
        private async Task<int> CheckMessageAsync(string Phone, string MessageCode)
        {
            try
            {
                var count = await _cacheservice.PGetSendMessageCountAsync(Phone);
                if (count > 0)//有验证码
                {
                    var redisPhone = await _cacheservice.GetPhoneMessageAsync(Phone, count);
                    if (redisPhone == null)
                    {
                        return 2;
                    }
                    if (redisPhone.Length > 0 && redisPhone == MessageCode)//验证码没过期，且验证码相同
                    {
                        return 1;
                    }
                    else return 2;
                }

                return 0;
            }
            catch (Exception ex)
            {

                var message = ex.ToString();
            }
            return 0;


        }
        public async Task<bool> AddUserByPhoneAsync(AddUserByPhone addUserByPhone)
        {
            var userPhone = await _LanQiQaDBContext.Users.Where(c => c.Phone == addUserByPhone.Phone).Select(o => o.Phone).FirstOrDefaultAsync();
            if (userPhone == null)
            {
                User user = new User()
                {
                    UserName = addUserByPhone.Phone,
                    Phone = addUserByPhone.Phone,
                    Password = addUserByPhone.Phone,
                    AvatarPath = "",
                    UserVip = 0
                };
                _LanQiQaDBContext.Users.Add(user);
                _LanQiQaDBContext.SaveChanges();
                return true;
            }
            return false;
        }
        public bool addFollow(int userId,int followID)
        
        {

         var data=   _LanQiQaDBContext.Follows.Where(o=>o.UserId== userId&&o.FollowedUserId== followID).Select(c=>c.FollowId).FirstOrDefault();
            if (data==0)
            {

               var AddFollow=new Follow()
                {
              UserId = userId,
             FollowedUserId = followID
            };
                _LanQiQaDBContext.Follows.Add(AddFollow);
              return  _LanQiQaDBContext.SaveChanges() > 0;
            }
            return false ;
        }

        public bool unfollow(int userId, int followId) 
        {
            var data = _LanQiQaDBContext.Follows.Where(o => o.UserId == userId && o.FollowedUserId == followId).Select(c=>c.FollowId).FirstOrDefault();
            if (data != null)
            {

                var AddFollow = new Follow()
                {
                    FollowId= data,
                    UserId = userId,
                    FollowedUserId = followId
                };
                _LanQiQaDBContext.Follows.Remove(AddFollow);
                return _LanQiQaDBContext.SaveChanges() > 0;
            }
            return false;
        }

        /* public int SendPhoneCode(LoginByPhone loginByPhone) 
         {
             _cacheservice.



         }*/

    }
}
